<?php
namespace App\Services\Office;

use App\Models\Music\Albums;
use App\Models\Music\Music;
use App\Models\Music\PdfFile;
use Excel;
use Chumper\Zipper\Zipper;
use Illuminate\Support\Facades\Mail;

use OSS\OssClient;
use OSS\Core\OssException;

class Office
{
    static public $instance;
    public $sp;
    static public function instance(){
        if(!self::$instance) self::$instance = new self();
        return self::$instance;
    }

    public function makeObject(){

    }

    //生成盖章pdf
    public function makeSignPdf($data,$full_name,$simple_name,$expired_time,$rand,$image,$fix_time,$sp_email,$online_time)
    {
        if($simple_name=='腾讯音乐'){
            $this->sp = new QQOffice();
        }else if($simple_name=='网易'){
            $this->sp = new WyOffice();
        }else if($simple_name == '360'){
            $this->sp = new RoundOffice();
        }else if($simple_name == '快手'){
            $this->sp = new KsOffice();
        }else if($simple_name == '唱吧'){
            $this->sp = new CbOffice();
        }else if($simple_name == '虾米音乐'){
            $this->sp = new AliOffice();
        }
        return $this->sp->makeSignPdf($data,$full_name,$simple_name,$expired_time,$rand,$image,$fix_time,$sp_email,$online_time);
    }

    //生成无章pdf
    public function makePdf($data,$full_name,$simple_name,$expired_time,$rand,$fix_time,$sp_email,$online_time){
        return $this->sp->makePdf($data,$full_name,$simple_name,$expired_time,$rand,$fix_time,$sp_email,$online_time);
    }


    //生成execl
    public function makeExecl($data,$full_name,$simple_name,$start_time,$expired_time,$rand,$online_time)
    {
        $this->sp->makeExecl($data,$full_name,$simple_name,$start_time,$expired_time,$rand,$online_time);
    }

    //发送邮件
    public function send($query,$full_name,$simple_name,$ossUrl,$album,$type) {
        if(!empty($album)){
            foreach($album as $v) {
                $res = Music::where('album', '=', $v['album'])->with('company', 'music_check', 'music_file', 'accompaniment_file', 'mv_file', 'video_file', 'karaoke_file')->where('check_status', '=', 2)->where('type_status', '=', $type)->get()->toArray();
                $r[] = $res;
            }
        }else{
            $r = [];
        }
        Mail::send('mail.index', ['ossUrl' => $ossUrl, 'music' => $query,'album'=>$r], function ($message) use ($full_name, $simple_name) {
            $message->to(['fenfa@kkkmusic.com'])->subject($full_name . '报表统计');
            $signPdf = PdfFile::where('type', '=', 1)->orderBy('id', 'desc')->select('name')->first()->toArray();
            $pdf = storage_path('exports/' . $signPdf['name'] . '/' . $simple_name . date('Y-m-d') . '-sign.pdf');
            $message->attach($pdf);
            $arr = explode('-', $signPdf['name']);
            if(!in_array($simple_name,config('sp.sp'))) {
                $execl = storage_path('exports/' . $simple_name . date('Y-m-d') . '-' . $arr[4] . '.xls');
                $message->attach($execl);
            }
        });
    }

    //上传文件
    public function oss($name,$filePath){
        $accessKeyId = "LTAIzVsHeKTYXO5v";
        $accessKeySecret = "BKMpZ3nCZVeXWDBbZAzH3mnht3dR8B";
        $endpoint = "http://oss-cn-beijing.aliyuncs.com";
        $bucket= "sanka-music";
        $object = $name;
        $filePath = $filePath;
        try{
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object, $filePath);
        } catch(OssException $e) {
           $error=[
               'msg' => $e->getMessage(),
               'code' => 400
           ];
           return $error;
        }
        $data = [
            'url' => "http://sanka-music.oss-cn-beijing.aliyuncs.com/".$name,
            'code' => 200
        ];
        return $data;
    }

    //下载文件
    public function ossLoad($query){
        $accessKeyId = "LTAIzVsHeKTYXO5v";
        $accessKeySecret = "BKMpZ3nCZVeXWDBbZAzH3mnht3dR8B";
        $endpoint = "http://oss-cn-beijing.aliyuncs.com";
        $bucket= "sanka-music";
        foreach($query as $v){
            $object = substr($v['cover'],strrpos($v['cover'],'/')+1);
            $image_size = getimagesize($v['cover']);
            $ext = substr($image_size['mime'],strrpos($image_size['mime'],'/')+1);
            $localfile = public_path('/images/'.$object.'.'.$ext);
            $options = array(
                OssClient::OSS_FILE_DOWNLOAD => $localfile
            );
            try{
                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                $ossClient->getObject($bucket, $object, $options);
            } catch(OssException $e) {
                $error=[
                    'msg' => $e->getMessage(),
                    'code' => 400
                ];
                return $error;
            }
        }
        return 200;
    }

    //生成压缩文件用于下载
    public function makeFileZip($signPath,$nosignPath){
        $zipper=new Zipper();
        $noFiles = glob(storage_path('/exports/'.$nosignPath.'/*'));
        $files = glob(storage_path('/exports/'.$signPath.'/*'));
        $zipper->make('zip/'.$nosignPath.'.zip')->add($noFiles);
        $zipper->make('zip/'.$signPath.'.zip')->add($files);
        $zipper->close();
    }

    //生成单曲音乐压缩文件
    public function makeMusicZip($query='',$simple_name,$cstatus,$ystatus,$bstatus,$mstatus,$kstatus,$dstatus,$rand,$album='',$type)
    {
        if(!empty($query) || !empty($album)){
            $zipper = new Zipper();
            $todir = './uploadMusic/' . $simple_name . date('Y-m-d') .'-'.$rand;
            @mkdir($todir, 0777);
            if (!empty($query)) {
                $this->makeSingleZip($query,$simple_name,$cstatus,$ystatus,$bstatus,$mstatus,$kstatus,$dstatus,$zipper,$todir);
            }
            if(!empty($album)){
                $this->makeAlbumZip($album,$simple_name,$cstatus,$ystatus,$bstatus,$mstatus,$kstatus,$dstatus,$zipper,$todir,$type);
            }
           $zipper->close();
        }
       $ossUrl = $this->oss($simple_name.date('Y-m-d').$rand,$todir.'.zip');
       return $ossUrl;
    }

    //生成单曲音乐压缩文件
    public function makeSingleZip($query,$simple_name,$cstatus,$ystatus,$bstatus,$mstatus,$kstatus,$dstatus,$zipper,$todir){
        foreach ($query as $v) {
            if ($v['music_file'] && $ystatus) {
                $musicExt = substr($v['music_file']['local_path'],strrpos($v['music_file']['local_path'],'.'));
               // $info = $this->fileInfo($v['music_file']['remote_path']);
                copy('./music/'.$v['music_file']['remote_path'], $todir.'/'.$v['title'].$musicExt);
                if(!empty($v['lyrics'])) {
                    $myfile = fopen($todir.'/'.$v['title'].".txt", "w");
                    fwrite($myfile, $v['lyrics']);
                }
                $object = substr($v['cover'],strrpos($v['cover'],'/')+1);
                $image_size = getimagesize($v['cover']);
                $ext = substr($image_size['mime'],strrpos($image_size['mime'],'/')+1);
                copy('./images/'.$object.'.'.$ext, $todir .'/'.$v['title'].'.'.$ext);
                $zipper->make($todir.'.zip')->folder($v['title'])->add($todir.'/'.$v['title'].$musicExt);
                $zipper->make($todir.'.zip')->folder($v['title'])->add($todir.'/'.$v['title'].'.txt');
                $zipper->make($todir.'.zip')->folder($v['title'])->add($todir.'/'.$v['title'].'.'.$ext);
            }
           if($v['mv_file'] && $mstatus){
               $mvExt = substr($v['mv_file']['local_path'],strrpos($v['mv_file']['local_path'],'.'));
               //$info = $this->fileInfo($v['mv_file']['remote_path']);
               copy('./music/'.$v['mv_file']['remote_path'],$todir.'/'.$v['title'].$mvExt);
               $zipper->make($todir.'.zip')->folder($v['title'])->add($todir.'/'.$v['title'].$mvExt);
           }
           if($v['accompaniment_file'] && $bstatus){
               $accExt = substr($v['accompaniment_file']['local_path'],strrpos($v['accompaniment_file']['local_path'],'.'));
               //$info = $this->fileInfo($v['accompaniment_file']['remote_path']);
               copy('./music/'.$v['accompaniment_file']['remote_path'],$todir.'/'.$v['title'].$accExt);
               $zipper->make($todir.'.zip')->folder($v['title'])->add($todir.'/'.$v['title'].$accExt);
           }
           if($v['video_file'] && $dstatus){
               $viExt = substr($v['video_file']['local_path'],strrpos($v['video_file']['local_path'],'.'));
               //$info = $this->fileInfo($v['video_file']['remote_path']);
               copy('./music/'.$v['video_file']['remote_path'],$todir.'/'.$v['title'].$viExt);
               $zipper->make($todir.'.zip')->folder($v['title'])->add($todir.'/'.$v['title'].$viExt);
           }
           if($v['karaoke_file'] && $kstatus){
               $kaExt = substr($v['karaoke_file']['local_path'],strrpos($v['karaoke_file']['local_path'],'.'));
               //$info = $this->fileInfo($v['karaoke_file']['remote_path']);
               copy('./music/'.$v['karaoke_file']['remote_path'],$todir.'/'.$v['title'].$kaExt);
               $zipper->make($todir.'.zip')->folder($v['title'])->add($todir.'/'.$v['title'].$kaExt);
           }
        }
    }

    //生成专辑音乐压缩文件
    public function makeAlbumZip($album,$simple_name,$cstatus,$ystatus,$bstatus,$mstatus,$kstatus,$dstatus,$zipper,$todir,$type){
        foreach($album as $v){
            $res = Music::where('album','=',$v['album'])->with('company', 'music_check', 'music_file', 'accompaniment_file', 'mv_file', 'video_file', 'karaoke_file')->where('check_status','=',2)->where('type_status','=',$type)->get()->toArray();
            $id = $res[0]['album_id'];
            $albumRes = Albums::where('id','=',$id)->get()->toArray();
            if(!empty($albumRes[0]['description'])) {
                $myfile = fopen($todir.'/'.$res[0]['album'].".txt", "w");
                fwrite($myfile, $albumRes[0]['description']);
            }
            $zipper->make($todir.'.zip')->folder($res[0]['album'])->add($todir.'/'.$res[0]['album'].'.txt');
            $object = substr($res[0]['cover'],strrpos($res[0]['cover'],'/')+1);
            $image_size = getimagesize($res[0]['cover']);
            $ext = substr($image_size['mime'],strrpos($image_size['mime'],'/')+1);
            copy('./images/'.$object.'.'.$ext, $todir.'/'.$res[0]['album'].'.'.$ext);
            $zipper->make($todir.'.zip')->folder($res[0]['album'])->add($todir.'/'. $res[0]['album'].'.'.$ext);
            foreach($res as $v){
                if(!empty($v['lyrics'])) {
                    $myfile = fopen($todir.'/'.$v['title'].".txt", "w");
                    fwrite($myfile, $v['lyrics']);
                }
                $zipper->make($todir.'.zip')->folder($res[0]['album'])->add($todir.'/'.$v['title'].'.txt');
                if($v['music_file'] && $ystatus){
                    $musicExt = substr($v['music_file']['local_path'],strrpos($v['music_file']['local_path'],'.'));
                   // $info = $this->fileInfo($v['music_file']['remote_path']);
                    copy('./music/'.$v['music_file']['remote_path'],$todir.'/'.$v['title'].$musicExt);
                    $zipper->make($todir.'.zip')->folder($v['album'])->add($todir.'/'.$v['title'].$musicExt);
                }
                if($v['mv_file'] && $mstatus){
                    $mvExt = substr($v['mv_file']['local_path'],strrpos($v['mv_file']['local_path'],'.'));
                   // $info = $this->fileInfo($v['mv_file']['remote_path']);
                    copy('./music/'.$v['mv_file']['remote_path'],$todir.'/'.$v['title'].$mvExt);
                    $zipper->make($todir.'.zip')->folder($v['album'])->add($todir.'/'.$v['title'].$mvExt);
                }
                if($v['accompaniment_file'] && $bstatus){
                    $accExt = substr($v['accompaniment_file']['local_path'],strrpos($v['accompaniment_file']['local_path'],'.'));
                   // $info = $this->fileInfo($v['accompaniment_file']['remote_path']);
                    copy('./music/'.$v['accompaniment_file']['remote_path'],$todir.'/'.$v['title'].$accExt);
                    $zipper->make($todir.'.zip')->folder($v['album'])->add($todir.'/'.$v['title'].$accExt);
                }
                if($v['video_file'] && $dstatus){
                    $viExt = substr($v['video_file']['local_path'],strrpos($v['video_file']['local_path'],'.'));
                    //$info = $this->fileInfo($v['video_file']['remote_path']);
                    copy('./music/'.$v['video_file']['remote_path'],$todir.'/'.$v['title'].$viExt);
                    $zipper->make($todir.'.zip')->folder($v['album'])->add($todir.'/'.$v['title'].$viExt);
                }
                if($v['karaoke_file'] && $kstatus){
                    $kaExt = substr($v['karaoke_file']['local_path'],strrpos($v['karaoke_file']['local_path'],'.'));
                    //$info = $this->fileInfo($v['karaoke_file']['remote_path']);
                    copy('./music/'.$v['karaoke_file']['remote_path'],$todir.'/'.$v['title'].$kaExt);
                    $zipper->make($todir.'.zip')->folder($v['album'])->add($todir.'/'.$v['title'].$kaExt);
                }
            }
        }
    }
    //文件信息详情
    public function fileInfo($data){
        $info ['dirname'] = rtrim(substr($data, 0, strrpos($data, '/')),"/");
        $info ['basename'] = ltrim(substr($data, strrpos($data, '/')),"/");
        $info ['extension'] = substr(strrchr($data, '.'), 1);
        $info ['filename'] = ltrim(substr($info ['basename'], 0, strrpos($info ['basename'], '.')),"/");
        return $info;
    }


}
